package com.example.weight.greenSeasons.flocculation;

import android.app.AppComponentFactory;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.SolidLiquid.shebeijiancha7_4jiancharen;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class xuningribaoyangChecker extends AppCompatActivity {
    private ExpandableLayout expand_1;
    private ExpandableLayout expand_2;
    private ExpandableLayout expand_3;

    private Button textView1;
    private Button textView2;
    private Button textView3;

    private CheckBox cb1, cb2, cb3, cb4, cb5, cb6;

    private String id1 = "-100", id2 = "-100", id3 = "-100", id4 = "-100", id5 = "-100", id6 = "-100";

    private String name, role, factory;

    private TextView dateEdit;
    private TitleBar titleBar;

    public void show1(View view) {
        if (expand_1.isExpanded()) {
            textView1.setText("+ 擦拭卫生");
        } else {
            textView1.setText("- 擦拭卫生");
        }

        expand_1.toggle();
    }

    public void show2(View view) {
        if (expand_2.isExpanded()) {
            textView2.setText("+ 擦拭清理冲洗内部");
        } else {
            textView2.setText("- 擦拭清理冲洗内部");
        }

        expand_2.toggle();
    }

    public void show3(View view) {
        if (expand_3.isExpanded()) {
            textView3.setText("+ 擦拭表面卫生清理冲洗内部");
        } else {
            textView3.setText("- 擦拭表面卫生清理冲洗内部");
        }

        expand_3.toggle();
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xuningribaoyang_checker);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        role = previousIntent.getStringExtra("role");
        factory = previousIntent.getStringExtra("factory");

        expand_1 = findViewById(R.id.expandable_1);
        expand_2 = findViewById(R.id.expandable_2);
        expand_3 = findViewById(R.id.expandable_3);
        textView1 = findViewById(R.id.button_1);
        textView2 = findViewById(R.id.button_2);
        textView3 = findViewById(R.id.button_3);
        dateEdit = findViewById(R.id.compost_editDate);

        cb1 = findViewById(R.id.cb1);
        cb2 = findViewById(R.id.cb2);
        cb3 = findViewById(R.id.cb3);
        cb4 = findViewById(R.id.cb4);
        cb5 = findViewById(R.id.cb5);
        cb6 = findViewById(R.id.cb6);

       TextView remark1 = findViewById(R.id.tv1);
       TextView remark2 = findViewById(R.id.tv2);
       TextView remark3 = findViewById(R.id.tv3);
       TextView remark4 = findViewById(R.id.tv4);
       TextView remark5 = findViewById(R.id.tv5);
       TextView remark6 = findViewById(R.id.tv6);

        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH) + 1; //第一个月从0开始，所以得到月份＋1
        Integer day = calendar.get(calendar.DAY_OF_MONTH);
        Integer hour24 = calendar.get(calendar.HOUR_OF_DAY);
        Integer minute = calendar.get(calendar.MINUTE);
        dateEdit.setText(year + "-" + month + "-" + day);

        titleBar = findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                if (!cb1.isChecked()) {
                    allDone(cb1.getText().toString());
                } else if (!cb2.isChecked()) {
                    allDone(cb2.getText().toString());
                } else if (!cb3.isChecked()) {
                    allDone(cb3.getText().toString());
                } else if (!cb4.isChecked()) {
                    allDone(cb4.getText().toString());
                } else if (!cb5.isChecked()) {
                    allDone(cb5.getText().toString());
                } else if (!cb6.isChecked()) {
                    allDone(cb6.getText().toString());
                } else {
                    xuningribaoyangChecker.this.finish();
                }
            }

            @Override
            public void onTitleClick(View v) {
            }

            @Override
            public void onRightClick(View v) {
            }
        });

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/flocculationProduceMaintenanceDay/getDailyRecords" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Log.d("jy", response);
                            JSONArray data;
                            if (jsonObject.get("data") != null && !jsonObject.get("data").toString().equals("null")) {
                                data = jsonObject.getJSONArray("data");
                                if (data.length() > 0) {
                                    for (int i = 0; i < data.length(); i++) {
                                        // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                                        JSONObject record = data.getJSONObject(i);
                                        // 得到 每个对象中的属性值
                                        if (record.get("equipmentName").equals(cb1.getText().toString())) {
                                            if (!record.get("examiner").toString().equals("null")) {
                                                cb1.setChecked(true);
                                                cb1.setEnabled(false);
                                                cb1.setTextColor(Color.GREEN);
                                            }
                                            id1 = record.get("id").toString();
                                            if (record.get("isNormal").equals("正常")) {
                                                TextView text = findViewById(R.id.tv1);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            } else {
                                                TextView text = findViewById(R.id.tv1);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        } else if (record.get("equipmentName").equals(cb2.getText().toString())) {
                                            if (!record.get("examiner").toString().equals("null")) {
                                                cb2.setChecked(true);
                                                cb2.setEnabled(false);
                                                cb2.setTextColor(Color.GREEN);
                                            }
                                            id2 = record.get("id").toString();
                                            if (record.get("isNormal").equals("正常")) {
                                                TextView text = findViewById(R.id.tv2);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            } else {
                                                TextView text = findViewById(R.id.tv2);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        } else if (record.get("equipmentName").equals(cb3.getText().toString())) {
                                            if (!record.get("examiner").toString().equals("null")) {
                                                cb3.setChecked(true);
                                                cb3.setEnabled(false);
                                                cb3.setTextColor(Color.GREEN);
                                            }
                                            id3 = record.get("id").toString();
                                            if (record.get("isNormal").equals("正常")) {
                                                TextView text = findViewById(R.id.tv3);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            } else {
                                                TextView text = findViewById(R.id.tv3);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        } else if (record.get("equipmentName").equals(cb4.getText().toString())) {
                                            if (!record.get("examiner").toString().equals("null")) {
                                                cb4.setChecked(true);
                                                cb4.setEnabled(false);
                                                cb4.setTextColor(Color.GREEN);
                                            }
                                            id4 = record.get("id").toString();
                                            if (record.get("isNormal").equals("正常")) {
                                                TextView text = findViewById(R.id.tv4);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            } else {
                                                TextView text = findViewById(R.id.tv4);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        } else if (record.get("equipmentName").equals(cb5.getText().toString())) {
                                            if (!record.get("examiner").toString().equals("null")) {
                                                cb5.setChecked(true);
                                                cb5.setEnabled(false);
                                                cb5.setTextColor(Color.GREEN);
                                            }
                                            id5 = record.get("id").toString();
                                            if (record.get("isNormal").equals("正常")) {
                                                TextView text = findViewById(R.id.tv5);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            } else {
                                                TextView text = findViewById(R.id.tv5);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        } else if (record.get("equipmentName").equals(cb6.getText().toString())) {
                                            if (!record.get("examiner").toString().equals("null")) {
                                                cb6.setChecked(true);
                                                cb6.setEnabled(false);
                                                cb6.setTextColor(Color.GREEN);
                                            }
                                            id6 = record.get("id").toString();
                                            if (record.get("isNormal").equals("正常")) {
                                                TextView text = findViewById(R.id.tv6);
                                                text.setText("正常");
                                                text.setTextColor(Color.parseColor("#018786"));
                                            } else {
                                                TextView text = findViewById(R.id.tv6);
                                                text.setText(record.get("remarks").toString());
                                                text.setTextColor(Color.parseColor("#B00020"));
                                            }
                                        }
                                    }
                                }
                            }
                            cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if (isChecked) {
                                        checkEquipment(cb1, remark1, id1);
                                    }
                                }
                            });
                            cb2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if (isChecked) {
                                        checkEquipment(cb2, remark2, id2);
                                    }
                                }

                            });
                            cb3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if (isChecked) {
                                        checkEquipment(cb3, remark3, id3);
                                    }
                                }

                            });
                            cb4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if (isChecked) {
                                        checkEquipment(cb4, remark4, id4);
                                    }
                                }

                            });
                            cb5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if (isChecked) {
                                        checkEquipment(cb5, remark5, id5);
                                    }
                                }
                            });
                            cb6.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView,
                                                             boolean isChecked) {
                                    // TODO Auto-generated method stub
                                    if (isChecked) {
                                        checkEquipment(cb6, remark6, id6);
                                    }
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(xuningribaoyangChecker.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    public void allDone(String equipment_name){
        new AlertDialog.Builder(this)
                .setTitle(" “"+ equipment_name +"” 未检查，是否退出")
                .setCancelable(false)
                .setNegativeButton("否", ((dialog, which) -> {
                }))
                .setPositiveButton("是", (dialog, which) ->{
                    xuningribaoyangChecker.this.finish();
                })
                .show();
    }

    public void checkEquipment(CheckBox equipment_name, TextView operatorRemark, String id) {
        final EditText equipment_problem = new EditText(this);
        equipment_problem.setHint("   输入问题:");
        new AlertDialog.Builder(this)
                //.setTitle(" “"+ equipment_name.getText().toString() +"” 已检查")
                .setTitle("操作人结论是否正确？如果有误请在下方填写问题")
                .setView(equipment_problem)
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->{
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                    equipment_name.setChecked(false);
                }
                ))
                .setPositiveButton("提交", (dialog, which) ->{
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/flocculationProduceMaintenanceDay/add_examiner";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.equals("200")){
                                            Toast.makeText(xuningribaoyangChecker.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                            equipment_name.setEnabled(false);
                                        }
                                        else
                                            Toast.makeText(xuningribaoyangChecker.this,
                                                    "1保存失败", Toast.LENGTH_SHORT).show();

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(xuningribaoyangChecker.this,
                                    "2保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", id);   ///------------------------这里要id
                            map.put("remarks", operatorRemark.getText().toString()+"_"+ equipment_problem.getText().toString());
                            map.put("examiner", name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}
